package com.test.spring2025_8_17.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class SseController {

    @GetMapping("/sse")
    public SseEmitter sse() {
        // 设置超时时间，0 表示不过期
        SseEmitter emitter = new SseEmitter(0L);

        // 模拟定时推送数据
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                emitter.send(SseEmitter.event()
                        .name("message") // 事件名
                        .data("服务器时间：" + System.currentTimeMillis()));
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        }, 0, 2, TimeUnit.SECONDS);

        return emitter;
    }
}

